/**
 * ALYR.NET 智能体规则自动检查器
 * 版权所有 (c) 2020-2025 ALYR.NET
 */

const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');
const UnifiedConfigManager = require('../config/unified-config-manager');

class AlyrAIRulesChecker {
  constructor() {
    this.violations = [];
    this.configManager = new UnifiedConfigManager();
    this.configManager.loadConfig();
    
    this.rules = {
      backend: {
        filePrefix: /^Alyr-[A-Z][a-zA-Z0-9]*\.(ts|js|spec\.ts)$/,
        copyrightRequired: true,
        securityCheck: true
      },
      frontend: {
        filePrefix: /^[A-Z][a-zA-Z0-9]*\.(tsx|jsx|ts|js)$/,
        copyrightRequired: false,
        antdOnly: true
      }
    };
  }

  // 🔍 快速规则检查 (智能体启动时调用)
  async quickCheck() {
    console.log(chalk.blue('🤖 Builder.Alyr.Net 智能体规则检查器启动...'));
    
    // 1. 检查规则文件是否存在
    const ruleFiles = [
      'user_rules.md',
      'project_rules.md',
      '智能体执行检查清单.md'
    ];
    
    for (const file of ruleFiles) {
      if (!await fs.pathExists(file)) {
        this.violations.push(`❌ 缺少规则文件: ${file}`);
      } else {
        console.log(chalk.green(`✅ 规则文件存在: ${file}`));
      }
    }
    
    // 2. 显示关键规则摘要
    this.showKeyRules();
    
    return this.violations.length === 0;
  }

  // 显示关键规则摘要（基于project_rules.md）
  showKeyRules() {
    const config = this.configManager.config;
    const componentLibs = config?.developmentStandards?.componentLibraries || {};
    
    console.log('\n🎯 Builder.Alyr.Net 开发规范核心要点:');
    console.log('📁 文件命名: 后端Alyr-前缀，前端常规命名');
    console.log('©️  版权声明: 后端强制，前端豁免');
    console.log(`🎨 组件规范: React(${componentLibs.react || 'ProComponents'}), Vue(${componentLibs.vue || 'Element Plus'}), Angular(${componentLibs.angular || 'Angular Material'}), 禁止any类型`);
    console.log('🔒 安全调用: 后端禁止直接axios/fetch');
    console.log('⚖️  自动执法: 违规文件立即删除\n');
  }

  // 🔍 文件类型检测
  detectFileType(filePath) {
    // 获取项目根目录路径
    const projectRoot = require('path').resolve(__dirname, '../..');
    const relativePath = require('path').relative(projectRoot, filePath);
    
    if (relativePath.includes('server/') || relativePath.includes('backend/')) {
      return 'backend';
    } else if (relativePath.includes('src/') || relativePath.includes('client/') || relativePath.includes('frontend/')) {
      return 'frontend';
    }
    return 'unknown';
  }

  // ✅ 验证文件命名
  validateFileName(filePath) {
    const fileName = path.basename(filePath);
    const fileType = this.detectFileType(filePath);
    const rules = this.rules[fileType];
    
    if (!rules) return true;
    
    const isValid = rules.filePrefix.test(fileName);
    if (!isValid) {
      this.violations.push(`❌ 文件命名违规: ${filePath}`);
      console.log(chalk.red(`❌ 文件命名违规: ${fileName}`));
      console.log(chalk.yellow(`   应该符合: ${rules.filePrefix}`));
    }
    
    return isValid;
  }

  // 🛡️ 版权检查
  async validateCopyright(filePath) {
    const fileType = this.detectFileType(filePath);
    const rules = this.rules[fileType];
    
    if (!rules || !rules.copyrightRequired) return true;
    
    const content = await fs.readFile(filePath, 'utf8');
    const hasCopyright = content.includes('ALYR.NET') && content.includes('版权所有');
    
    if (!hasCopyright) {
      this.violations.push(`❌ 缺少版权声明: ${filePath}`);
      console.log(chalk.red(`❌ 缺少版权声明: ${filePath}`));
    }
    
    return hasCopyright;
  }

  // 🎯 Ant Design 组件检查
  async validateAntdUsage(filePath) {
    if (!filePath.endsWith('.tsx') && !filePath.endsWith('.jsx')) return true;
    
    const content = await fs.readFile(filePath, 'utf8');
    
    // 检查是否使用了非 Ant Design 组件
    const forbiddenImports = [
      '@mui/material',
      '@material-ui/core',
      'react-bootstrap',
      'semantic-ui-react'
    ];
    
    for (const forbidden of forbiddenImports) {
      if (content.includes(forbidden)) {
        this.violations.push(`❌ 禁用组件库: ${filePath} 使用了 ${forbidden}`);
        console.log(chalk.red(`❌ 禁用组件库: ${forbidden} in ${filePath}`));
        return false;
      }
    }
    
    return true;
  }

  // 🚫 any 类型检查
  async validateNoAnyType(filePath) {
    if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx')) return true;
    
    const content = await fs.readFile(filePath, 'utf8');
    const hasAnyType = /:\s*any\b|<any>|any\[\]/.test(content);
    
    if (hasAnyType) {
      this.violations.push(`❌ 使用any类型: ${filePath}`);
      console.log(chalk.red(`❌ 禁止使用any类型: ${filePath}`));
    }
    
    return !hasAnyType;
  }

  // 🔧 自动修复
  async autoFix(filePath) {
    console.log(chalk.blue(`🔧 尝试自动修复: ${filePath}`));
    
    const fileType = this.detectFileType(filePath);
    if (fileType === 'backend') {
      await this.addCopyrightHeader(filePath);
    }
    
    // 其他自动修复逻辑...
  }

  // 📄 添加版权声明
  async addCopyrightHeader(filePath) {
    const content = await fs.readFile(filePath, 'utf8');
    
    if (content.includes('ALYR.NET')) return;
    
    const copyrightHeader = `/**
 * Builder.Alyr.Net 轻量化内容管理平台
 * 版权所有 (c) 2020-2025 ALYR.NET
 * 严格禁止未授权使用、复制或分发
 */

`;
    
    await fs.writeFile(filePath, copyrightHeader + content);
    console.log(chalk.green(`✅ 已添加版权声明: ${filePath}`));
  }

  // 📊 生成检查报告
  generateReport() {
    console.log(chalk.blue('\n📊 智能体规则检查报告:'));
    
    if (this.violations.length === 0) {
      console.log(chalk.green('🎉 所有规则检查通过！智能体可以安全执行任务。'));
      return true;
    } else {
      console.log(chalk.red(`❌ 发现 ${this.violations.length} 个违规项:`));
      this.violations.forEach(violation => {
        console.log(chalk.red(`   ${violation}`));
      });
      return false;
    }
  }
}

// 🚀 智能体启动检查
async function aiStartupCheck() {
  const checker = new AlyrAIRulesChecker();
  
  console.log(chalk.blue('🤖 智能体启动中...正在加载ALYR.NET开发规范...'));
  
  const isValid = await checker.quickCheck();
  const reportResult = checker.generateReport();
  
  if (isValid && reportResult) {
    console.log(chalk.green('\n✅ 智能体已准备就绪，严格遵循ALYR.NET开发规范！'));
    return true;
  } else {
    console.log(chalk.red('\n❌ 智能体启动失败，请修复规则违规后重试！'));
    return false;
  }
}

// 导出模块
module.exports = {
  AlyrAIRulesChecker,
  aiStartupCheck
};

// 如果直接运行此脚本
if (require.main === module) {
  aiStartupCheck().then(success => {
    process.exit(success ? 0 : 1);
  });
}